import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store' // Import the Vuex store
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import i18n from './lang'

// Add navigation guard to handle authentication
router.beforeEach((to, from, next) => {
  // Check if the route requires authentication
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // Check if user is logged in (check Vuex store for user)
    const isAuthenticated = store.state.user && store.state.token;
    
    if (!isAuthenticated) {
      // Redirect to login page if not authenticated
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      // Check user role if specified
      const userRole = store.state.user.userType;
      if (to.meta.role && userRole !== to.meta.role) {
        // Redirect to home if user doesn't have the right role
        next({ path: '/' })
      } else {
        next()
      }
    }
  } else {
    // Allow access to routes that don't require authentication
    next()
  }
})

const app = createApp(App)

app.use(router)
app.use(store)
app.use(ElementPlus)
app.use(i18n)

app.mount('#app')